<template>
  <div>
    <el-row>
      <el-col :span="8">
        <el-alert
          :title="warning_title"
          type="warning"
          show-icon
          :closable="false"
        ></el-alert>
      </el-col>
      <el-col :span="12" style="padding-left: 30px; padding-top: 2px">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="small"
          @click="handleAdd"
          >新增进度</el-button
        >
      </el-col>
    </el-row>
    <el-table
      :id="'case' + activeName"
      :data="dataList"
      v-loading="listLoading"
      :fit="false"
      size="small"
      row-key="id"
      highlight-current-row
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column
        align="left"
        label="进度名称"
        width="360px"
        prop="name"
      ></el-table-column>
      <el-table-column
        align="center"
        label="结案标志"
        width="120px"
        prop="is_final"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.is_final == true">结案</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="300px">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="handleEdit(scope)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            size="mini"
            icon="el-icon-delete"
            @click="handleDelete(scope)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :visible.sync="dialogVisible" :title="getTitle" width="600px">
      <el-form
        :model="form"
        :rules="formRules"
        ref="formRef"
        label-width="100px"
        label-position="right"
        style="width: 95%; padding: 0 30px"
      >
        <el-form-item label="案件配置项" prop="name">
          <el-input v-model="form.name" placeholder="案件配置项" clearable />
        </el-form-item>
        <el-form-item label="父项" prop="parent">
          <el-select v-model="form.parent" placeholder="配置父项" clearable>
            <el-option
              v-for="item in parents"
              :label="item.name"
              :value="item.id"
              :key="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="案件终结标志" prop="is_final">
          <el-switch v-model="form.is_final"></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="danger" size="small" @click="dialogVisible = false"
          >取消</el-button
        >
        <el-button type="primary" size="small" @click="handleSave"
          >保存</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Sortable from "sortablejs";
import {
  getProgressList,
  addProgress,
  updateProgress,
  delProgress,
  updateBatchProgress,
  getParentProgressList,
} from "@/api/case";
const defaultForm = {
  id: null,
  name: "",
  parent: null,
  is_final: false,
  case_type: null,
  sort: null,
};

export default {
  name: "Phase",
  components: {
    Sortable,
  },
  props: {
    activeName: {
      required: true,
      type: Number,
    },
    listLoading: {
      required: true,
      type: Boolean,
      default() {
        return true;
      },
    },
    dataList: {
      type: Array,
      default() {
        return [];
      },
    },
  },
  data() {
    return {
      form: Object.assign({}, defaultForm),
      formRules: {
        name: [{ required: true, message: "请输入配置项", trigger: "blur" }],
      },
      title: "案件进度配置",
      warning_title: "进度配置：可上下拖拉重新排序",
      dialogVisible: false,
      parents: [],
      dialogType: "new",
    };
  },
  computed: {
    getTitle() {
      return this.dialogType === "edit"
        ? `编辑${this.title}`
        : `新增${this.title}`;
    },
    // currentPage: {
    //   get() {
    //     return this.page;
    //   },
    //   set(val) {
    //     this.$emit("update:page", val);
    //   },
    // },
    // pageSize: {
    //   get() {
    //     return this.limit;
    //   },
    //   set(val) {
    //     this.$emit("update:limit", val);
    //   },
    // },
  },
  mounted() {
    this.rowDrop();
    this.getParentProgress();
  },
  methods: {
    getParentProgress() {
      const params = {
        case_type: this.activeName,
      };
      getParentProgressList(params)
        .then((res) => {
          this.parents = res;
        })
        .catch((error) => {
          this.$message.error("获取父项失败");
        });
    },
    handleAdd() {
      this.form = Object.assign({}, defaultForm);
      console.log("activeName：", this.activeName);
      this.dialogType = "new";
      this.dialogVisible = true;

      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    handleEdit(scope) {
      this.form = Object.assign({}, scope.row);
      this.dialogType = "edit";

      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除该信息吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delProgress(row.id);

          this.dataList.splice($index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
          this.$message.error("删除失败!");
        });
    },
    // 保存操作
    async handleSave() {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;

        const isEdit = this.dialogType === "edit";
        if (isEdit) {
          const res = await updateProgress(this.form);
          console.log(isEdit, res);
          const index = this.dataList.findIndex((v) => v.id === res.id);
          this.dataList.splice(index, 1, res);
        } else {
          this.form.case_type = +this.activeName;
          //设置最大值
          let max = 0;
          if (this.dataList.length > 0) {
            const sorts = this.dataList.map((item) => {
              return item.sort;
            });
            max = Math.max.apply(null, sorts);
          }

          this.form.sort = max + 1;
          const res = await addProgress(this.form);
          const { id } = res;
          if (id > 0) {
            this.$emit("progress", { case_type: this.activeName });
          }
        }

        const { name } = this.form;
        this.dialogVisible = false;
        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>进度配置: ${name}</div>
            `,
          type: "success",
        });
      });
    },
    //排序
    updateSorts(dataList) {
      const updateData = dataList.map((item) => {
        return { id: item.id, sort: item.sort };
      });
      console.log(updateData);
      const data = {
        update_ids: updateData,
      };
      updateBatchProgress(data)
        .then((res) => {
          this.$message.success("排序成功");
        })
        .catch((error) => {
          this.$message.error("排序失败!" + error.response.data.message);
          // console.log(error);
        });
    },
    rowDrop() {
      const tbody = document.querySelector(
        "#case" + this.activeName + " .el-table__body-wrapper tbody"
      );
      const _this = this;
      Sortable.create(tbody, {
        fallbackOnBody: true,
        onEnd({ newIndex, oldIndex }) {
          console.log(newIndex, oldIndex);
          const currRow = _this.dataList.splice(oldIndex, 1)[0];
          _this.dataList.splice(newIndex, 0, currRow);
          _this.dataList.map((item, index) => {
            item.sort = index + 1;
            return item;
          });
          _this.updateSorts(_this.dataList);
        },
      });
    },
    handleProgress() {
      this.$emit("progress", { case_type: this.activeName });
    },
    // handleCurrentChange(val) {
    //   this.$emit("pagination", { page: val, limit: this.pageSize });
    //   if (this.autoScroll) {
    //     scrollTo(0, 800);
    //   }
    // },
  },
};
</script>

<style scoped>
</style>
